package com.zhiyu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.zhiyu.api.ReturnMsg;
import com.zhiyu.api.ReturnResult;
import com.zhiyu.dao.ILoginMapper;
import com.zhiyu.entity.SysUser;
import com.zhiyu.service.webApi.ILoginService;
import com.zhiyu.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service(version = "1.0.0")
@Slf4j
public class LoginServiceImpl implements ILoginService {

    @Resource
    private ILoginMapper iLoginMapper;

    /**
     * 根据用户信息生成token（用户登录）
     * @param param
     * @return
     */
    @Override
    public ReturnResult getTokenByUser(Map<String, Object> param) {
        ReturnResult returnResult = ReturnResult.success();
        try {
            // 用户返回的数据：包含token和状态冻结标志位
            Map resultMap = new HashMap();
            // 根据登录名和密码查询用户信息
            SysUser sysUser = iLoginMapper.getUserByLoginInfo(param);
            if (sysUser == null) {
                returnResult.setCode(ReturnMsg.ERROR.getCode());
                returnResult.setMsg("获取token失败");
            } else {
                // 每次登录更新最近一次登录时间
                iLoginMapper.updateLastLoginTimeByUserId(sysUser.getId());
                String token = JwtUtil.sign(sysUser.getId());
                resultMap.put("token",token);
                resultMap.put("frozenFlag",sysUser.getFrozenFlag());
                returnResult.setData(resultMap);
                return returnResult;
            }
        } catch (Exception e) {
            log.error("获取token发生异常",e);
            returnResult.setCode(ReturnMsg.ERROR.getCode());
            returnResult.setMsg("获取token发生异常");
            return returnResult;
        }
        return returnResult;
    }

}
